import { defineStore } from 'pinia'
import type { ImageModel, UserPreferences, AppState } from '@/types'

// 应用主状态管理
export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    loading: false,
    selectedImages: [],
    searchKeyword: '',
    selectedTags: [],
    currentView: 'grid',
    sidebarCollapsed: false
  }),

  getters: {
    hasSelectedImages: (state) => state.selectedImages.length > 0,
    selectedImageCount: (state) => state.selectedImages.length,
    isGridView: (state) => state.currentView === 'grid',
    isListView: (state) => state.currentView === 'list'
  },

  actions: {
    // 加载状态管理
    setLoading(loading: boolean) {
      this.loading = loading
    },

    // 图片选择管理
    selectImage(image: ImageModel) {
      const index = this.selectedImages.findIndex(img => img.id === image.id)
      if (index > -1) {
        this.selectedImages.splice(index, 1)
      } else {
        this.selectedImages.push(image)
      }
    },

    selectAllImages(images: ImageModel[]) {
      this.selectedImages = [...images]
    },

    clearSelectedImages() {
      this.selectedImages = []
    },

    removeSelectedImage(imageId: number) {
      const index = this.selectedImages.findIndex(img => img.id === imageId)
      if (index > -1) {
        this.selectedImages.splice(index, 1)
      }
    },

    // 搜索状态管理
    setSearchKeyword(keyword: string) {
      this.searchKeyword = keyword
    },

    setSelectedTags(tags: string[]) {
      this.selectedTags = tags
    },

    addSelectedTag(tag: string) {
      if (!this.selectedTags.includes(tag)) {
        this.selectedTags.push(tag)
      }
    },

    removeSelectedTag(tag: string) {
      const index = this.selectedTags.indexOf(tag)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      }
    },

    clearSearch() {
      this.searchKeyword = ''
      this.selectedTags = []
    },

    // 视图状态管理
    setCurrentView(view: 'grid' | 'list') {
      this.currentView = view
    },

    toggleView() {
      this.currentView = this.currentView === 'grid' ? 'list' : 'grid'
    },

    // 侧边栏状态管理
    setSidebarCollapsed(collapsed: boolean) {
      this.sidebarCollapsed = collapsed
    },

    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
    }
  },

  persist: {
    key: 'app-store',
    storage: localStorage,
    paths: ['currentView', 'sidebarCollapsed', 'selectedTags']
  }
})

// 用户偏好设置管理
export const useUserStore = defineStore('user', {
  state: (): { preferences: UserPreferences } => ({
    preferences: {
      theme: 'auto',
      language: 'zh-CN',
      pageSize: 24,
      defaultSortBy: 'createdAt',
      defaultSortDir: 'desc',
      autoSave: true,
      showTutorial: true
    }
  }),

  getters: {
    isDarkTheme: (state) => {
      if (state.preferences.theme === 'auto') {
        return window.matchMedia('(prefers-color-scheme: dark)').matches
      }
      return state.preferences.theme === 'dark'
    },

    isLightTheme: (state) => {
      if (state.preferences.theme === 'auto') {
        return !window.matchMedia('(prefers-color-scheme: dark)').matches
      }
      return state.preferences.theme === 'light'
    }
  },

  actions: {
    updatePreferences(preferences: Partial<UserPreferences>) {
      this.preferences = { ...this.preferences, ...preferences }
    },

    setTheme(theme: 'light' | 'dark' | 'auto') {
      this.preferences.theme = theme
    },

    setLanguage(language: 'zh-CN' | 'en-US') {
      this.preferences.language = language
    },

    setPageSize(size: number) {
      this.preferences.pageSize = size
    },

    setDefaultSort(sortBy: string, sortDir: 'asc' | 'desc') {
      this.preferences.defaultSortBy = sortBy
      this.preferences.defaultSortDir = sortDir
    },

    toggleAutoSave() {
      this.preferences.autoSave = !this.preferences.autoSave
    },

    hideTutorial() {
      this.preferences.showTutorial = false
    }
  },

  persist: {
    key: 'user-preferences',
    storage: localStorage
  }
})

// API请求状态管理
export const useApiStore = defineStore('api', {
  state: () => ({
    requestCount: 0,
    errors: [] as Array<{
      id: string
      message: string
      timestamp: number
      url?: string
      status?: number
    }>
  }),

  getters: {
    isLoading: (state) => state.requestCount > 0,
    hasErrors: (state) => state.errors.length > 0,
    latestError: (state) => state.errors[state.errors.length - 1]
  },

  actions: {
    startRequest() {
      this.requestCount++
    },

    endRequest() {
      if (this.requestCount > 0) {
        this.requestCount--
      }
    },

    addError(error: {
      message: string
      url?: string
      status?: number
    }) {
      this.errors.push({
        id: Date.now().toString(),
        timestamp: Date.now(),
        ...error
      })

      // 限制错误记录数量
      if (this.errors.length > 10) {
        this.errors = this.errors.slice(-10)
      }
    },

    clearErrors() {
      this.errors = []
    },

    removeError(id: string) {
      const index = this.errors.findIndex(error => error.id === id)
      if (index > -1) {
        this.errors.splice(index, 1)
      }
    }
  }
})